<?php
class Players_model
    extends CI_Model
    {
    private $sort_mode    = 0;        //режим сортировки
    private $fields_array = array();  //поля вывода 
    private $query_array  = array();  //поля вывода с заданными именами (определны через AS)
    private $table_headers = array(); //имена полей вывода и заголовки таблиц
    private $segments     = '';
    private $page         = '';
    private $where_string = array();
    private $ht_server = '';
    //private $user='';

    function __construct()
        {
        parent::__construct();
        //$this->user=$this->auth->getUser();
        //получаем значения массивов полей в зависимости от класса юзера
        $this->get_user_fields($this->auth->hasAccess('players/show_players'));

        if (($this->input->post(
                 'submit_sort_mode')) && ($this->input->post('sort_mode'))) //если выбран режим изменения сортировки
            {
            if ($this->input->post('sort_mode') == 'multi')
                $this->session->set_userdata('sort_mode', '1');
            else
                $this->session->set_userdata('sort_mode', '0');
            }

        $this->sort_mode=$this->session->userdata('sort_mode');

        $this->_parse_url_request($this->uri->uri_to_assoc()); //вырезаем значения сортировки из строки УРЛ

        $sort_directions=array();

        foreach ($this->segments as $key => $value)
            {
            if (isset($this->table_headers[$key])) //если значение есть в массиве имен полей
                $sort_directions[$this->table_headers[$key]]=$value;
            }

        $this->view->set('sort_directions', $sort_directions); //устанавливаем переменную имен полей для вьювера
        $this->view->set("sort_mode", $this->sort_mode);       //переменная для вьювера режим сортировки
        }

    function _parse_url_request($segments)
        {
        $this->segments=$segments;

        if (isset($this->segments['page']))
            {
            $this->page=(int)$this->segments['page'];
            unset ($this->segments['page']);
            }
        }

    /*--------------------------------------------------------*/
    function getall()
        {

        //если задан поиск
        $search_array=array();

        if ($this->input->post('send_search') && $this->input->post('search_params'))
            {
            $search_array=$this->input->post('search_params', TRUE);
            $this->session->unset_userdata('user_search');
            $this->session->set_userdata('user_search', $search_array);
            }
        else
            {
            if ($this->session->userdata('user_search'))
                {
                $search_array=$this->session->userdata('user_search');
                }
            }

        if ($this->input->post('reset_search')) //если выбран сброс значений поиска
            {
            $this->session->unset_userdata('user_search');

            $search_array=array();
            }

        $this->view->set('form_values', $search_array); //устанавливаем переменную для вьювера

        $sort_search_string=array();                    //флаг сортировки при поиске по дефалту

        if (!empty($search_array))                      //если заданы параметры поиска
            {
            if (isset($search_array['skill']))          //Обработка поисковых параметров
                {
                $skill=$search_array['skill'];
                unset ($search_array['skill']);
                }

            if (isset($search_array['skill_values']))
                {
                $skill_values=$search_array['skill_values'];
                unset ($search_array['skill_values']);
                }
            if ($skill)
            foreach ($skill as $num => $kod)
                {
                if (isset($this->fields_array[$kod]))
                    $search_array[$kod]=$skill_values[$num];
                }

            unset($skill, $skill_values);

            foreach ($search_array as $field => $search_string)
                {
                //if (isset($this->fields_array[$field]))
                    {
                    if (is_array($search_string))
                        {
                        foreach ($search_string as $limit => $limit_data)
                            {
                            if (!$limit_data)
                                continue; //если значение пусто

                            if ($limit == 'from')
                                {
                                $operand='>=';
                                }
                            elseif ($limit == 'to')
                                {
                                $operand='<=';
                                }

                            $this->where_string[]
                                =$this->fields_array[$field] . " " . $operand . " " . $this->db->escape($limit_data);
                            }
                        }
                    else
                        {
                            if ($field!='only_actual')
                            $this->where_string[]=$this->fields_array[$field] . " = " . $this->db->escape($search_string);
                            else $this->where_string[]="FetchDate >= ". $this->db->escape(date("Y-m-d H:i:s", (time()-(60*60*24*30))));
                            
                        }

                    if ($this->where_string && $field!='only_actual')
                        $sort_search_string[]
                            =$this->fields_array[$field] . ' DESC '; //устанавливаем флаг для сортировки по дефалту
                    }
                }
            }

        if ($this->where_string)
            $this->where_string="WHERE " . implode(" AND ", $this->where_string);
        else
            $this->where_string='';

        $sort_string='';

        if ($this->segments)                                //если выбрана сортировка
            {
            if ($this->sort_mode == 1)                      //если режим сортировки мульти
                {
                foreach ($this->segments as $key => $value) //для каждого направления сортировки
                    {
                    if ($value != '')
                        {
                        $this->get_sort_simple($key, $value, $sort_string);
                        }
                    }
                }
            else //если режим сортировки - одиночный
                {
                reset ($this->segments);
                $key=key($this->segments);

                if (isset($this->fields_array[$key]) && $this->segments[$key] != '' && $key != 'page')
                    {
                    $this->get_sort_simple($key, $this->segments[$key], $sort_string);
                    }
                }
            }

        if (!$this->where_string)
            {
            if (!$sort_string)
                $sort='ORDER BY ' . $this->fields_array['age'] . ', ' . $this->fields_array['days'];
            else
                $sort='ORDER BY ' . $sort_string;
            }
        else
            {
            if (!$sort_string){
                if ($sort_search_string) $sort='ORDER BY ' . implode(",", $sort_search_string);
            }
            else
                $sort='ORDER BY ' . $sort_string;
            }

        if (isset($this->page) && $this->page != '') //вычисляем текущую строку пагинации
            $current_page=$this->page . ",";
        else
            $current_page="";


        //$query_string="SELECT * FROM players ".$this->where_string." ".$sort." LIMIT ".$current_page." 20";
        
        //СОБИРАЕМ ЗАПРОС ДЛЯ ВЫВОДА ИГРОКОВ
        $query_string
              ="SELECT " . implode(",",
                                   $this->query_array) . " FROM Players 
                                   LEFT JOIN `TeamDetails` AS `team` ON `Players`.`OwningTeam`=`team`.`TeamID`
                                   LEFT JOIN `Specialty` ON `Players`.`Specialty`=`Specialty`.`SpecialtyID`
                                   "
            . $this->where_string . " " . $sort . " LIMIT " . $current_page . " 20";
        $query=$this->db->query($query_string);

        return $query;
        }

    /*--------------------------------------------------------*/
    function getPlayer($PlayerID = '')
        {
        if (!$PlayerID)
            return false;

        $PlayerID=(int)$PlayerID;
        $this->load->library('table');
        $query_string="SELECT " . implode(",",$this->query_array) . " 
        FROM Players 
        LEFT JOIN `TeamDetails` AS `team` ON `Players`.`OwningTeam`=`team`.`TeamID`
        LEFT JOIN `Specialty` ON `Players`.`Specialty`=`Specialty`.`SpecialtyID`
        WHERE PlayerID=$PlayerID";
        $result      =$this->db->query($query_string);
        $player=$result->result_array();
        return ($player[0]);
        }
    /*--------------------------------------------------------*/
    function pagination()
        {
        $this->load->library('pagination');
        $query_segment='';
        $i            =0;

        foreach ($this->segments as $key => $value)
            {
            if ($key != 'page')
                $query_segment.='/' . $key . '/' . $value;
            else
                break;

            $i=$i + 2;
            }

        $query_segment.='/';
        $config['base_url']     =site_url() . 'players/show_players' . $query_segment . 'page/';
        $result                 =$this->db->query("Select COUNT(1) as cnt FROM Players " . $this->where_string);
        $total_rows             =$result->row();
        $config['total_rows']   =$total_rows->cnt;
        $config['per_page']     ='20';
        $config['uri_segment']  =$i + 4;
        $config['num_links']    =5;

        $config['first_link']   ='В начало';
        $config['last_link']    ='В конец';
        $config['next_link']    ='>';
        $config['prev_link']    =' < ';
        $config['cur_tag_open'] ='<b>';
        $config['cur_tag_close']='</b> | ';
        $config['num_tag_open'] ='';
        $config['num_tag_close']=' | ';

        $this->pagination->initialize($config);

        return 'Записей отобрано: ' . $total_rows->cnt . '<br />' . $this->pagination->create_links() . '<br />';
        }
    /*--------------------------------------------------------*/
    function render_table($query)
        {
        if (!$query)
            return 'Request Error!';

        $this->load->library('table');

        $heading=$this->table_headers;

        foreach ($heading as $key => $cell)
            {
            $heading[$key]=$this->_render_link($key, $cell);
            }

        if ($this->auth->hasAccess('players/show_players', 'view_all'))
            $heading['Loko']=$this->_render_link('', 'Loko', 1); //добавляем поля без сортировки

        $sort_num=1;

        $heading['name']=array
            ('data'=>
            $heading['name'],
            'width'=>'400px'
            );

        /*$tmpl=array
            (
            'table_open'              => '<table class="art-article" cellspacing="0">',
            'heading_cell_name_start' => '<th width="300px;">',
            'row_start'               => '<tr class="even">'
            );
         */
        //массив цветов
        $colors_array[1]="#ff2400";
        $colors_array[] ="#ff4f00";
        $colors_array[] ="#efd334";
        $colors_array[] ="#34c924";
        $colors_array[] ="#42aaff";
        $colors_array[] ="#1560bd";
        $colors_array[] ="#735184";

        foreach ($this->segments as $key => $head)
            {
            if (isset($heading[$key]))
                {
                if (!is_array($heading[$key]))
                    $heading[$key]=array
                        (
                        'data'=>$heading[$key],
                        'style' => 'background:'.$colors_array[$sort_num]
                        );
                 $sort_num++;
                }
            }

        $this->table->set_template($tmpl);
        //скрываем заголовки
        $this->_hideTable($heading, array('id', 'teamid'));
        
        if (!$this->auth->hasAccess('players/show_players', 'view_all')){
            
            $this->_hideTable($heading, array('kp','df','pm','wg','ps','sc','sp','date'));
        
        }
 
        $this->table->set_heading($this->_prep_for_table($heading));

        $fn=$this->table_headers; //присваиваем имена полей в запросе
        
        foreach ($query->result_array()as $row)
            {
            //$row[$this->table_headers['id']] = anchor("/players/player_info/" . $row[$this->table_headers['id']], $row[$this->table_headers['id']]);
            $row[$fn['name']] = anchor("/players/player_info/" . $row[$fn['id']],
                                                        $row[$fn['name']]);
            
            if (strtotime($row[$fn['date']])<(time()-(60*60*24*30)))
                   $row[$fn['name']]='<a href="http://www'.$this->ht_server.'.hattrick.org/Club/?TeamID='.$row[$fn['teamid']].'&SendMessage=true&ft_popuplink=true">
                   <img border="0" alt="Неактуальный" src="'.site_url().'images/cleardot.gif" class="nonactual"></a> '.$row[$fn['name']];
            $row[$fn['flag']]='<img src="' . site_url() . 'images/flags/' .$row[$fn['flag']] . '_mini.gif">';
            
            //скрываем поля
            $this->_hideTable($row, array($fn['id'],$fn['teamid']));

           if (!$this->auth->hasAccess('players/show_players', 'view_all')){
            
                $this->_hideTable($row, array($fn['kp'],$fn['df'],$fn['pm'],$fn['wg'],$fn['ps'],$fn['sc'],$fn['sp'],$fn['date']));
        
            }
            if ($this->auth->hasAccess('players/show_players', 'view_all'))
                $row['Loko']=$this->count_skill($row); //вычисляем полезность игрока

            $this->table->add_row($this->_prep_for_table($row));
            }

        return $this->table->generate();
        }
    /*--------------------------------------------------------*/

    function _set_sort_direction($value)
        {
        if ($value != 'age' && $value != 'days')
            {
            $param['up']  ='up';
            $param['down']='des';
            }
        else
            {
            $param['up']  ='des';
            $param['down']='up';
            }

        return $param;
        }

    function _render_link($sort_string = '', $data = '', $parse = 0, $image = '0')
        {
        $query_string='';
        $flag_change =false;

        if (!$parse) //если нужно парсить ссылку
            {
            if ($this->sort_mode == 1)
                {
                foreach ($this->segments as $key => $value)
                    {
                    if ($key == $sort_string)
                        {
                        $param=$this->_set_sort_direction($key);

                        if ($value == $param['down'] || $value == '')
                            $value=$param['up'];
                        else
                            $value=$param['down'];

                        $flag_change=true;
                        }

                    $query_string.=$key . '/' . $value . '/';
                    }
                }
            else
                {
                $value='';

                if (isset($this->segments[$sort_string]))
                    $value=$this->segments[$sort_string];

                $param=$this->_set_sort_direction($value);

                if ($value == $param['down'])
                    $value=$param['up'];
                else
                    $value=$param['down'];

                $flag_change=true;
                $query_string.=$sort_string . '/' . $value . '/';
                }

            if (!$flag_change)
                {
                $param=$this->_set_sort_direction($sort_string);
                $sort_string.='/' . $param['down'];
                }
            else
                $sort_string='';

            if ($this->page)
                {
                if (substr($query_string . $sort_string, (strlen($query_string . $sort_string) - 1), 1) == '/')
                    $last_slash='';
                else
                    $last_slash='/';

                $page_link=$last_slash . 'page/' . $this->page;
                }
            else
                $page_link='';

            $link_string=$query_string . $sort_string . $page_link;
            }
        else
            {
            $link_string='';
            }

        if ($image)
            {
            //превращаем текст в картинку
            $angel=mb_strlen($data) / 2 >= 4 ? $angel='/90' : $angel='';
            $data ='<img src="' . site_url() . 'players/image/' . $data . $angel . '" border="0">';
            }

        if (!$parse)
            return anchor('/players/show_players/' . $link_string, $data);
        else
            return $data;
        }
    /*--------------------------------------------------------*/
    function get_sort_simple($sort = '', $direction = '', &$sort_string)
        {
        if (isset($this->fields_array[$sort]))
            {
            if ($sort_string != '')
                $sort_string.=', ';

            $sort_string.=' ' . $this->fields_array[$sort] . ' ';

            if ($direction == 'des')
                $sort_string.=' DESC';

            if ($sort == 'age' && !isset($this->segments['days']))
                {
                $sort_string.=' ,' . $this->fields_array['days'] . ' ASC';
                }

            return $sort_string;
            }
        }
    /*--------------------------------------------------------*/
    function _hideTable(&$data, $clear_data)
        {
        if (is_array($clear_data))
            foreach ($clear_data as $clear)
                {
                unset ($data[$clear]);
                }
        else
            unset ($data[$clear_data]);
        }
        
    function _hideFields()
    {
        
    }    

    function get_user_fields($view_mode = '')
        {
        if (!$view_mode)
            return;

        $fields=array
            (
            'id'     => 'PlayerID',
            'name'   => 'PlayerName',
            'flag'   =>  'team.CountryID',
            'teamid' => 'OwningTeam',
            'team'   => 'OwningTeamName',
            'tsi'    => 'TSI',
            'age'    => '(Age+FLOOR((AgeDays + DATEDIFF(NOW(),FetchDate))/112))',
            'days'   => '(`AgeDays`+ DATEDIFF(NOW(),`FetchDate`))%112',
            'form'   => 'PlayerForm',
            'salary' => 'Salary',
            'st'     => 'StaminaSkill',
            'lid'    => 'Leadership',
            'spec'   => 'SpecialtyShort',
            'kp'   => 'KeeperSkill',
            'df'   => 'DefenderSkill',
            'pm'   => 'PlaymakerSkill',
            'wg'   => 'WingerSkill',
            'ps'   => 'PassingSkill',
            'sc'   => 'ScorerSkill',
            'sp'   => 'SetPiecesSkill',
            'date' => 'FetchDate',
            );

        $headers=array
            (
            'id'     => 'ID',
            'name'   => 'Имя игрока',
            'flag'   => 'Флаг',
            'teamid'   => 'OwningTeam',
            'team'   => 'Ком',
            'tsi'    => 'TSI',
            'age'    => 'Лет',
            'days'   => 'Дней',
            'form'   => 'ФР',
            'salary' => 'З/П',
            'st'     => 'ВН',
            'lid'    => 'Лид',
            'spec'   => 'Спец',
            'kp'   => 'ВР',
            'df'   => 'ДФ',
            'pm'   => 'ПЗ',
            'wg'   => 'ФЛ',
            'ps'   => 'ПС',
            'sc'   => 'НП',
            'sp'   => 'СТ',
            'date' => 'Обновл',
            );
            
        /*
        $fields['view_all']=array
            (
            'kp'   => 'KeeperSkill',
            'df'   => 'DefenderSkill',
            'pm'   => 'PlaymakerSkill',
            'wg'   => 'WingerSkill',
            'ps'   => 'PassingSkill',
            'sc'   => 'ScorerSkill',
            'sp'   => 'SetPiecesSkill',
            'date' => 'FetchDate'
            );

        $headers['view_all']=array
            (
            'kp'   => 'ВР',
            'df'   => 'ДФ',
            'pm'   => 'ПЗ',
            'wg'   => 'ФЛ',
            'ps'   => 'ПС',
            'sc'   => 'НП',
            'sp'   => 'СТ',
            'date' => 'Обновл'
            );

        foreach ($view_mode as $view)
            {
            $this->fields_array = array_merge($this->fields_array, $fields[$view]);
            $this->table_headers=array_merge($this->table_headers, $headers[$view]);
            } */
        $this->fields_array=$fields;
        $this->table_headers=$headers;
        foreach ($this->fields_array as $key => $field)
            {
            $this->query_array[$key]=$field . ' AS `' . $this->table_headers[$key] . '` ';
            }
        }

    function count_skill($row = '')
        {
        
            //!!!!!!!!!!!!!!!!!!
            $Stamina=1;  //заменить!!!!!!!
            
        if (!$row)
            return;

        $alpha=1;
        $beta =1;
        $gamma=1;
        $alpha=0.22 + 0.13 * $Stamina; //Выносливость влияет на ПЗ
        $beta =0.7 + 0.05 * $Stamina;  //Выносливость влияет на другие скилы, кроме вратаря
        $gamma=1;                      //выносливость влияет на вратаря
        /*
        *gK| goalKeeper
{skills} = 0.75 * {goalkeeping} * {?} + 0.25 * {defending} * {?}

cD| centralDefender, normal
{skills} = 0.15 * {playmaking} * {?} + (0.7 * {defending} + 0.15 * {passing}) * {?}

cD| centralDefender, offensive
{skills} = 0.3 * {playmaking} * {?} + (0.6 * {defending} + 0.1 * {passing}) * {?}

wB| wingBack, normal
{skills} = 0.1 * {playmaking} * {?} + (0.6 * {defending} + 0.3 * {winger}) * {?}

wB| wingBack, offensive
{skills} = 0.15 * {playmaking} * {?} + (0.5 * {defending} + 0.35 * {winger}) * {?}

iM| innerMidfielder, defensive
{skills} = 0.65 * {playmaking} * {?} + (0.25 * {defending} + 0.1 * {passing}) * {?}

iM| innerMidfielder, normal
{skills} = 0.7 * {playmaking} * {?} + (0.15 * {defending} + 0.15 * {passing}) * {?}

iM| innerMidfielder, offensive
{skills} = 0.65 * {playmaking} * {?} + (0.1 * {defending} + 0.25 * {passing}) * {?}

Wg| Winger, towards middle
{skills} = 0.35 * {playmaking} * {?} + (0.35 * {winger} + 0.15 * {passing} + 0.15 * {defending}) * {?}

Wg| Winger, normal
{skills} = 0.2 * {playmaking} * {?} + (0.5 * {winger} + 0.2 * {passing} + 0.1 * {defending}) * {?}

Wg| Winger, offensive
{skills} = 0.1 * {playmaking} * {?} + (0.6 * {winger} + 0.3 * {passing}) * {?}

Fw| Forward, defensive
If Technical : {skills} = 0.5 * {playmaking} * {?} + (0.3 * {passing} + 0.3 * {scoring}) * {?}
Otherwise : {skills} = 0.5 * {playmaking} * {?} + (0.2 * {passing} + 0.3 * {scoring}) * {?}

Fw| Forward, towards wing
{skills} = (0.4 * {scoring} + 0.2 * {passing} + 0.4 * {winger}) * {?}

Fw| Forward, normal
{skills} = (0.7 * {scoring} + 0.2 * {passing} + 0.1 * {winger}) * {?} 
        * 
        */


        //                               kp     pm      df      ps      wg     sc
        $koef['Kp']=array
            (
            0.75,
            0,
            0.25,
            0,
            0,
            0
            );

        $koef['cDf_n']=array
            (
            0,
            0.15,
            0.7,
            0.15,
            0,
            0
            );

        $koef['cDf_o']=array
            (
            0,
            0.3,
            0.6,
            0.1,
            0,
            0
            );

        $koef['cDf_w']=array
            (
            0,
            0,
            0,
            0,
            0,
            0
            ); //!!!!

        $koef['wDf_n']=array
            (
            0,
            0.1,
            0.6,
            0,
            0.3,
            0
            );

        $koef['wDf_o']=array
            (
            0,
            0.15,
            0.5,
            0,
            0.35,
            0
            );

        $koef['wDf_d']=array
            (
            0,
            0,
            0,
            0,
            0,
            0
            ); //!!!!     

        $koef['wDf_m']=array
            (
            0,
            0,
            0,
            0,
            0,
            0
            );

        $koef['In_d']=array
            (
            0,
            0.65,
            0.25,
            0.1,
            0,
            0
            );

        $koef['In_n']=array
            (
            0,
            0.7,
            0.15,
            0.15,
            0,
            0
            );

        $koef['In_o']=array
            (
            0,
            0.65,
            0.1,
            0.25,
            0,
            0
            );

        $koef['In_w']=array
            (
            0,
            0,
            0,
            0,
            0,
            0
            ); //!!!! 

        $koef['Wg_m']=array
            (
            0,
            0.35,
            0.15,
            0.15,
            0.35,
            0
            );

        $koef['Wg_n']=array
            (
            0,
            0.2,
            0.1,
            0.2,
            0.5,
            0
            );

        $koef['Wg_o']=array
            (
            0,
            0.1,
            0,
            0.3,
            0.6,
            0
            );

        $koef['Wg_d']=array
            (
            0,
            0,
            0,
            0,
            0,
            0
            ); //!!!!

        //if ($row['SpecialtyShort'] == 'T')
        if ($row['Спец'] == 'T')
            $koef['Fw_d']=array
                (
                0,
                0.5,
                0,
                0.3,
                0,
                0.3
                );
        else
            $koef['Fw_d']=array
                (
                0,
                0.5,
                0,
                0.2,
                0,
                0.3
                );

        $koef['Fw_w']=array
            (
            0,
            0,
            0,
            0.2,
            0.4,
            0.4
            );

        $koef['Fw_n']=array
            (
            0,
            0,
            0,
            0.2,
            0.1,
            0.7
            );

        $skill=0;

        foreach ($koef as $skillName => $k)
            {
            $temp = $k[0] * $row[$this->table_headers['kp']] * $gamma + $k[1] * $row[$this->table_headers['pm']]
                * $alpha + ($k[2] * $row[$this->table_headers['df']] + $k[3] * $row[$this->table_headers['ps']] + $k[3]
                               * $row[$this->table_headers['wg']] + $k[4] * $row[$this->table_headers['sc']]) * $beta;

            if ($temp > $skill)
                {
                $skill    =$temp;
                $mainSkill=$skillName;
                }
            }

        return $mainSkill . '[' . $skill . ']';
        }

    function export_to_excel($query = '', $filename = '')
        {
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');

        $pExcel=new PHPExcel();
        $pExcel->getProperties()->setTitle('title')->setDescription('description');

        // Assign cell values
        $pExcel->setActiveSheetIndex(0);
        $fields=$query->field_data();
        $aSheet=$pExcel->getActiveSheet();
        $aSheet->setTitle('Первый лист');

        $arr_rows=range('A', 'Z');
        $rowNum  =1;
        $colNum  =0;

        foreach ($fields as $field)
            {
            $aSheet->setCellValue($arr_rows[$colNum] . $rowNum, $field->name);
            $colNum++;
            }

        //$objPHPExcel->getActiveSheet()->setCellValue('A1', 'cell value here');

        //устанавливаем ширину
        $aSheet->getColumnDimension('A')->setWidth(15);
        $aSheet->getColumnDimension('B')->setWidth(25);

        foreach ($query->result()as $row)
            {
            $colNum = 0;
            $rowNum++;

            foreach ($row as $value)
                {
                $aSheet->setCellValue($arr_rows[$colNum] . $rowNum, $value);
                $colNum++;
                }
            }

        // Save it as an excel 2003 file
        $objWriter=IOFactory::createWriter($pExcel, 'Excel5');
        //$objWriter->save('nameoffile.xls'); 
        header ("Content-Type: application/vnd.ms-excel\r\n");
        header ("Content-Disposition: attachment; filename=\"my.xls\"\r\n");
        header ("Cache-Control: max-age=0\r\n");
        $objWriter->save('php://output');
        }
        
    function set_HT_server()
        {
        if ($this->input->post('submit_ht_server'))
        {
            $this->ht_server=$this->input->post('ht_server');
            $this->session->set_userdata('ht_server',$this->ht_server);
            
        }
        else $this->ht_server='';
        $this->ht_server=$this->session->userdata('ht_server');
        return $this->ht_server;
    }
    
        //функция перевода массива из ассоциативного в числовой
    function _prep_for_table($row)
    {
        $out=array();
        foreach ($row as $value)    
        {
            $out[]=$value;
        }
        return $out;
    }
    }
?>